<template>
  <div class="upload-box">
    <!-- 上传 -->
    <el-upload :id="uuid"
               :accept="fileType.join(',')"
               :action="serverUpload ? uploadUrl : uploadData.actionUrl"
               :before-upload="beforeImageUpload"
               :class="['upload', drag ? 'no-border' : '']"
               :data="serverUpload ? {} : uploadData.requestData"
               :disabled="disabled || percentageShow"
               :drag="drag"
               :headers="serverUpload ? uploadHeaders : {}"
               :multiple="false"
               :name="fileName"
               :on-error="handleUploadError"
               :on-progress="handleUploadProgress"
               :on-success="handleUploadSuccess"
               :show-file-list="false">

      <!-- 上传进度 -->
      <el-progress v-if="percentageShow" :color="percentageColors" :percentage="percentage" :width="percentageWidth" type="circle"/>

      <!-- 上传操作 -->
      <template v-else>
        <!--  有图片 -->
        <template v-if="modelValue">
          <img :src="modelValue" alt="" class="upload-image"/>
          <div class="upload-handle" @click.stop>
            <div v-if="!disabled" class="handle-icon" @click="handleUploadFun">
              <SvgIcon icon="ep:plus"/>
            </div>
            <div class="handle-icon" @click="handlePreviewFun">
              <SvgIcon icon="ep:zoom-in"/>
            </div>
            <div v-if="showDelete && !disabled" class="handle-icon" @click="handleDeleteFun">
              <SvgIcon icon="ep:delete"/>
            </div>
          </div>
        </template>
        <!-- 没有图片时的处理 -->
        <SvgIcon v-else icon="ep:plus"/>
      </template>

      <template #tip>
        <div v-if="showTip && !disabled" class="el-upload__tip">
          <span v-if="!customTip || customTip.length == 0">只能上传 {{ acceptTypes }} 文件，且不超过 {{ fileSize }}MB。</span>
          <span v-else>{{ customTip }}</span>
        </div>
      </template>
    </el-upload>

    <!-- 预览 -->
    <el-image-viewer v-if="viewerShow" :teleported="true" :url-list="[modelValue]" @close="viewerShow = false"/>
  </div>
</template>

<script lang="ts" setup>
import { computed, PropType, ref, watchEffect } from 'vue';
import { toAnyString } from '@/utils';
import { getToken, getTokenHeader } from '@/utils/auth.ts';
import { getRequestUrl } from '@/utils/axios/axios-service.ts'
import useUpload, { UploadItemData } from '@/components/upload/src/use-upload.ts';
import { SvgIcon } from '@/components/icon';

defineOptions({name: 'UploadImage'});

const props = defineProps({
  modelValue: String,
  // 拖拽上传
  drag: {
    type: Boolean,
    default: true
  },
  // 是否禁用上传组件
  disabled: {
    type: Boolean,
    default: false
  },
  // 是否显示提示信息
  showTip: {
    type: Boolean,
    default: true
  },
  // 自定义提示信息
  customTip: {
    type: String,
    default: ''
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 10
  },
  // 文件类型
  fileType: {
    type: Array as PropType<string[]>,
    default: () => ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp']
  },
  // 组件高度
  height: {
    type: String,
    default: '64px'
  },
  // 组件宽度
  width: {
    type: String,
    default: '64px'
  },
  // 组件边框圆角
  borderRadius: {
    type: String,
    default: '6px'
  },
  // 是否显示删除按钮
  showDelete: {
    type: Boolean,
    default: false
  },
  // 是否服务端上传
  serverUpload: {
    type: Boolean,
    default: false
  },
  fileName: {
    type: String,
    default: 'file'
  },
  // 图标保存到七牛云的路径
  uploadPath: {
    type: String,
    default: 'uploads'
  },
  // 是否重命名图片名称
  rename: {
    type: Boolean,
    default: true
  },
});

// 生成组件唯一id
const uuid = ref('id-' + toAnyString());

// 服务端上传地址
const uploadUrl = ref(getRequestUrl('/v1/oss'));
// 服务端上传头部
const uploadHeaders = computed(() => {
  let headers = {};
  let header = getTokenHeader();
  if (header) {
    headers[header] = getToken();
  }
  return headers;
});

// 可接受的文件类型
const acceptTypes = computed(() => {
  let accepts = props.fileType || []
  let types: string[] = []
  for (let item of accepts) {
    types.push((item as String).split('/')[1])
  }
  return types.join(' / ')
});

// 图片预览
const viewerShow = ref(false);
const handlePreviewFun = () => {
  viewerShow.value = true
};

// 上传进度宽度处理
const percentageWidth = computed(() => {
  return parseInt(props.width.replace('px', '')) - 10;
});

// 定义事件
const emit = defineEmits(['update:modelValue', 'change']);
const itemData = ref<UploadItemData[]>([]);

// 上传函数
const {
  uploadData, uploadOptions, percentage, percentageShow, percentageColors,
  beforeImageUpload, handleUploadSuccess, handleUploadExceed, handleUploadError, handleUploadProgress
} = useUpload(itemData.value, (url: string) => {
  let newData: UploadItemData = {
    id: undefined,
    content: url,
    orderNum: Date.now(),
  }
  itemData.value.push(newData);
  // 上传成功回调
  emit('update:modelValue', url);
  emit('change', url);
});

// watchEffect监听
watchEffect(() => {
  uploadOptions.limit = 1;
  uploadOptions.fileSize = props.fileSize;
  uploadOptions.fileTypes = props.fileType;
  uploadOptions.uploadPath = props.uploadPath;
  uploadOptions.rename = props.rename;
  uploadOptions.serverUpload = props.serverUpload;
})

// 开始上传
const handleUploadFun = () => {
  itemData.value.splice(0, itemData.value.length);
  const dom = document.querySelector(`#${uuid.value} .el-upload__input`)
  dom && dom.dispatchEvent(new MouseEvent('click'))
}

// 删除图片
const handleDeleteFun = () => {
  itemData.value.splice(0, itemData.value.length);
  emit('update:modelValue', '')
  emit('change', '');
};

</script>
<style lang="scss" scoped>
.is-error {
  .upload {
    :deep(.el-upload),
    :deep(.el-upload-dragger) {
      border: 1px dashed var(--el-color-danger) !important;

      &:hover {
        border-color: var(--el-color-primary) !important;
      }
    }
  }
}

:deep(.disabled) {
  .el-upload,
  .el-upload-dragger {
    cursor: not-allowed !important;
    background: var(--el-disabled-bg-color);
    border: 1px dashed var(--el-border-color-darker) !important;

    &:hover {
      border: 1px dashed var(--el-border-color-darker) !important;
    }
  }
}

.upload-box {
  .no-border {
    :deep(.el-upload) {
      border: none !important;
    }
  }

  :deep(.upload) {
    .el-upload {
      width: v-bind(width);
      height: v-bind(height);
      border-radius: v-bind(borderRadius);
      border: 1px dashed var(--el-border-color-darker);

      &:hover {
        border-color: var(--el-color-primary);

        .upload-handle {
          opacity: 1;
        }
      }

      .el-upload-dragger {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        padding: 0;
        overflow: hidden;
        background-color: transparent;
        border: 1px dashed var(--el-border-color-darker);
        border-radius: v-bind(borderRadius);

        &:hover {
          border: 1px dashed var(--el-color-primary);
        }
      }

      .el-upload-dragger.is-dragover {
        background-color: var(--el-color-primary-light-9);
        border: 1px dashed var(--el-color-primary) !important;
      }

      .upload-image {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }

      .upload-handle {
        position: absolute;
        width: v-bind(width);
        height: v-bind(height);
        border-radius: v-bind(borderRadius);
        cursor: default;
        display: inline-flex;
        justify-content: center;
        align-items: center;
        opacity: 0;
        font-size: 16px;
        background-color: var(--el-overlay-color-lighter);
        transition: opacity var(--el-transition-duration);

        .handle-icon {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 0 3%;
          color: aliceblue;
        }
      }
    }
  }

  .el-upload__tip {
    line-height: 18px;
    color: var(--el-text-color-regular);
  }
}
</style>
